<?php

namespace app\common\controller;

use app\admin\service\UserService;
use app\BaseController;
use app\model\DepartmentAdminModel;
use app\model\TrainLogModel;
use app\model\UserModel;
use app\model\not_del\UserModel as NotDelUserModel;
use think\App;

class User extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new UserModel();
    }


    /**
     * 批量修改部门
     * @return false|string
     */
    public function updateDepartment(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|用户ID' => 'require',
                'department_id|部门ID' => 'require',
            ]);
            $this->mode->where('id','in',$param['id'])->update([
                'department_id' => $param['department_id'],
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(),$e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $where[] = ['company_id', '=', $this->userData['company_id']];
            $where[] = ['areas_id', '=', $this->userData['areas_id']];
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $where[] = ['department_id', '=', $this->userData['department_id']];
            if (!empty($param['role_id'])) {
                $where[] = ['role_id', '=', $param['role_id']];
            }
            if (!empty($param['type'])) {
                $where[] = ['type', '=', $param['type']];
            }
            if (!empty($param['status'])) {
                $where[] = ['status', '=', $param['status']];
            }
            if (!empty($param['name'])) {
                $where[] = ['name|username', 'like', '%' . $param['name'] . '%'];
            }
            if (isset($param['sex']) && strlen($param['sex']) > 0) {
                $where[] = ['sex', '=', $param['sex']];
            }
            $data = $this->mode->where($where)->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 添加账号
     * @return false|string
     */
    public function add(): bool|string
    {
        $param = $this->request->param();
        try {
            $this->validate($param, $this->mode->addValidate());
            $param['company_id'] = $this->userData['company_id'];
            $param['areas_id'] = $this->userData['areas_id'];
            $param['unit_id'] = $this->userData['unit_id'];
            $param['time'] = time();
            $param['password'] = encrypt_password($param['password']);
            $this->mode->insert($param);
            return success([], '添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑账号
     * @return false|string
     */
    public function update(): bool|string
    {
        try {
            $param = $this->request->param();
            if (isset($param['id'])){
                $info = $this->mode->find($param['id']);
            }else{
                $info = $this->mode->find($this->userData['id']);
            }
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['password'])) {
                if (!validatePassword($param['password'])) throw new \Exception('密码长度不符合要求，8-18位字符');
                $param['password'] = encrypt_password($param['password']);
            }
            if (!empty($param['backup_phone']) && !empty($param['code'])) {
                if (!cache('phoneCodeLogin_'.md5($param['code'].$param['backup_phone']))) throw new \Exception('手机验证码错误！');
                if ($info->backup_phone != $param['backup_phone']){
                    $is_exist = $this->mode->where('backup_phone','=',$param['backup_phone'])->value('id');
                    if ($is_exist) throw new \Exception('该手机号已绑定其他账号！');
                }
            }else{
                unset($param['code']);
                unset($param['backup_phone']);
            }
//            $param = array_filter($param);
            $update = [];
            if (isset($param['is_login'])) {
                $update['is_login'] = $param['is_login'];
            }
            if (isset($param['is_code'])) {
                $update['is_code'] = $param['is_code'];
            }
            if (isset($param['is_scan'])){
                $update['is_scan'] = $param['is_scan'];
            }
            if (!empty($update)){
                $this->mode->where('unit_id','=',$this->userData['unit_id'])->update($update);
            }
            $info->save($param);
            return success([], '更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除账号
     * @return false|string
     */
    public function del(): bool|string
    {
        $id = $this->request->param('id');
        try {
            $this->mode->where('id', '=', $id)->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 用户信息
     * @return false|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');
            if (!$id){
                $id = $this->userData['id'];
            }
            $NotDelUserModel = new NotDelUserModel();
            $info = $NotDelUserModel->with([
                'unitName',
                'roleName',
                'userTag' => function($query){
                    $query->with(['tag']);
                }
            ])->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            if ($info['role_id'] == 0) $info['role_name'] = '超级管理员';
            $UserService = new UserService($this->app);
            $NotDelDepartmentAll = $UserService->getDepartmentAffiliationAll2($this->userData['unit_id'],[$info['department_id']]);
            $info['department_name'] = $NotDelDepartmentAll['department_data'][$info['department_id']]['all_name'] ?? '';
            $DepartmentAdminModel = new DepartmentAdminModel();
            if ($info['role_mode'] == 3){
                $department_admin = $DepartmentAdminModel->where('department_id','=',$info['department_id'])->with(['userName'])->select()->toArray();
                $department_admin = array_column($department_admin,'user_name');
            }else{
                $department_admin = $DepartmentAdminModel->where('uid','=',$info['id'])->with(['Department'])->select()->toArray();
                $department_admin = array_column($department_admin,'department_name');
            }
            $info['department_admin'] = implode('、',$department_admin);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 创建超管账号
     * @return bool|string
     */
    public function generateAccount(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'area|区域标识' => 'require'
            ]);
            $filePath = app()->getRootPath()."/public/username_config.txt";
            $content = file_get_contents($filePath);
            $data = json_decode($content, true);
            $accountData = $this->getRandAccount($data,$param['area']);
            $is = $this->mode->where('username','=',$accountData['username'])->value('id');
            $i = 0;
            while ($is){
                if ($i > 10) break;
                $accountData = $this->getRandAccount($data,$param['area']);
                $is = $this->mode->where('username','=',$accountData['username'])->value('id');
                $i++;
            }
            $content = json_encode($accountData['data'], true);
            file_put_contents($filePath, $content);
            return success(['username' => $accountData['username'], 'password' => env('ADMIN_PASSWORD'), 'time' => time()]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    public function getRandAccount($data,$area): array
    {
        if (empty($data)){
            $data[$area] = 100;
        }
        $username = 'Admin' . $area . $data[$area]++;
        return [
            'data' => $data,
            'username' => $username,
        ];
    }

    /**
     * 管理选择器
     * @return bool|string
     */
    public function adminSelector(): bool|string
    {
        try {
            $data = $this->mode->where([
                ['role_mode','=',1],
                ['unit_id','=',$this->userData['unit_id']],
            ])->field('id,name')->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 管理选择器(含咨询师)
     * @return bool|string
     */
    public function adminSelector2(): bool|string
    {
        try {
            $data = $this->mode->where([
                ['role_mode','=',2],
                ['unit_id','=',$this->userData['unit_id']],
            ])->field('id,name')->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 解绑手机号
     * @return bool|string
     */
    public function UnbindPhone(): bool|string
    {
        try {
            $info = $this->mode->find($this->userData['id']);
            if (empty($info->backup_phone)) throw new \Exception('请先绑定');
            $info->backup_phone = '';
            $info->save();
            return success([],'解绑成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 心理训练记录
     * @return bool|string
     */
    public function TrainLog(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require',
            ]);
            if (!empty($param['type'])){
                $where[] = ['type','=',$param['type']];
            }
            if (!empty($param['emo'])){
                $where[] = ['emo','=',$param['emo']];
            }
            if (!empty($param['content'])){
                $where[] = ['content','like','%'.$param['content'].'%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['name'])){
                $uid = $this->mode->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['name','like','%'.$param['name'].'%'],
                ])->column('id');
                if (!empty($uid)){
                    $where[] = ['uid','in',$uid];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $TrainLogModel = new TrainLogModel();
            $query = $TrainLogModel->where($where);
            $data = $query->with(['user'])->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 添加心理训练记录
     * @return bool|string
     */
    public function addTrainLog(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'type|类型' => 'require',
                'emo|表情' => 'require',
                'content|内容' => 'require'
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            $TrainLogModel = new TrainLogModel();
            $TrainLogModel->insert($param);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除心理训练记录
     * @return bool|string
     */
    public function delTrainLog(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require'
            ]);
            $TrainLogModel = new TrainLogModel();
            if (is_array($param['id'])){
                $TrainLogModel->where('id','in',$param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $info = $TrainLogModel->find($param['id']);
                $info->save([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}
